﻿using JFTest.Communacation;
using JFTest.Communication;
using JFTest.CommunicationService;
using JFTest.utils;
using JFTest.Utils;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using WindowsFormTest.Entity;
using WindowsFormTest.utils;




namespace WindowsFormTest
{
    public delegate void ShowInfo(string info);//接收到的消息呈现在主界面上
    public partial class Form1 : Form
    {
        public delegate string MyDelegate(string status);

        public ModbusClient mdbusClient;

        
        private readonly Point[] numberPoints = new Point[4];
        private readonly Rectangle squareRect = new Rectangle(300, 100, 80, 80);
        public static event ShowInfo showInfo;
        ThreeDCam threeDCam;

        TcpClientDevice tcpClientDevice;

        HPDeviceCommunicator alg;
        private int dataCount = 0;
        private Random random = new Random();
        public Form1()
        {
            InitializeComponent();
            mdbusClient = new ModbusClient("192.168.1.240", 502);
            mdbusClient.ReConnect();

            InitializePoints();
            showInfo += ShowInfoStatus;
            //threeDCam = new ThreeDCam();
            //threeDCam.ConnectAsync("127.0.0.1", 6666,3000);
            tcpClientDevice = new TcpClientDevice("3D相机", "192.168.250.99", 8080);
            alg = new HPDeviceCommunicator("COM3");
            //alg.Open();
        }



        private void uiButton3_Click(object sender, EventArgs e)
        {
            Thread thread1 = new Thread(new ParameterizedThreadStart(doWork));
            thread1.Start(1);

            Thread thread2 = new Thread(new ParameterizedThreadStart(doMoreWork));
            thread2.Start("对象类型，啥都行");


        }
        public void doWork(Object status)
        {
            string str = "参数为：" + status;
            Console.WriteLine(str);
        }
        public void doMoreWork(Object status)
        {
            string str = "参数为：" + status;
            Console.WriteLine(str);
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 有参数的异步方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton4_Click(object sender, EventArgs e)
        {
            MyDelegate myDelegate = new MyDelegate(withParam);
            IAsyncResult result = myDelegate.BeginInvoke("asycTest", null, null);
            string finallyResult = myDelegate.EndInvoke(result); // 等待异步方法执行完成
            Console.WriteLine("异步方法执行完成，结果为：" + finallyResult);
        }
        public string withParam(string status)
        {
            string str = "参数为：" + status;
            Console.WriteLine(str);
            return "现在时间为：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "传入参数为：" + status;
        }

        private async Task uiButton1_Click()
        {
            uiRichTextBox1.AppendText("开始执行任务1" + Environment.NewLine);

            await Method1Asyc();

            uiRichTextBox1.AppendText("开始执行任务2" + Environment.NewLine);
            string result = await Method2Asyc("param2");

            uiRichTextBox1.AppendText("任务2执行完成，返回值：" + result + DateTime.Now.ToString("yyyyMMddHHmmss.fff") + Environment.NewLine);
        }

        public async Task Method1Asyc()
        {
            await Task.Delay(1000); // 模拟异步操作
            uiRichTextBox1.AppendText("Method1Asyc 执行完成" + DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
        }
        public async Task<string> Method2Asyc(string s)
        {
            await Task.Delay(2000); // 模拟异步操作
            uiRichTextBox1.AppendText("Method2Asyc 执行完成" + DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
            return "Method2Asyc 返回值:" + s + DateTime.Now.ToString("yyyyMMddHHmmss.fff");
        }

        private void uiButton5_Click(object sender, EventArgs e)
        {
            if (uiStatusBox1.Status == 1)
            {
                uiStatusBox1.Status = 2;
            }
            else
            {
                uiStatusBox1.Status = 1;
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            uiButton1_Click();
        }

        private void uiButton6_Click(object sender, EventArgs e)
        {


        }



        private void uiButton7_Click(object sender, EventArgs e)
        {
            bool[] result = mdbusClient.ReadCoils(0, 10);
            coilValue.Text = "线圈值为：" + result[0].ToString();
        }

        private void uiButton8_Click(object sender, EventArgs e)
        {
            mdbusClient.WriteSingleCoil(0, true);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            uiLabel1.Text = mdbusClient.isConnected ? "连接成功" : "连接失败";

            light_plc.Status = tcpClientDevice.IsConnected ? 1 : 4;
        }

        private void uiButton9_Click(object sender, EventArgs e)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            var task = Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    if (cts.Token.IsCancellationRequested)
                    {
                        Console.WriteLine("Task canceled" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        break;
                    }
                    Console.WriteLine($"Task running: {i}" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    Thread.Sleep(500);
                }
            }, cts.Token);
            Thread.Sleep(2000);
            cts.Cancel();

        }

        private void uiButton10_Click(object sender, EventArgs e)
        {
            string numStr = uiTextBox1.Text;
            Double num = Double.Parse(numStr);
            int[] result = DoubleToRegisters(num);

            uiTextBox2.Text = String.Join(",", result);
        }
        private int[] DoubleToRegisters(double value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bytes); // 转为大端序

            int[] regs = new int[4];
            for (int i = 0; i < 4; i++)
            {
                regs[i] = (bytes[i * 2] << 8) | bytes[i * 2 + 1];
            }
            return regs;
        }

        private void BtnLoad_Click(object sender, EventArgs e)
        {

        }
        private void InitializePoints()
        {
            // 设置四个序号的位置
            numberPoints[0] = new Point(50, 50);   // 序号1
            numberPoints[1] = new Point(250, 80);  // 序号2
            numberPoints[2] = new Point(150, 200); // 序号3
            numberPoints[3] = new Point(400, 250); // 序号4
        }

        private void uiButton11_Click(object sender, EventArgs e)
        {
            // 配置连接字符串（带密码）
            string connectionString = "localhost:6379,password=admin.2025,allowAdmin=true,connectTimeout=5000";

            // 初始化Redis连接
            RedisHelper.Initialize(connectionString);

            // 注册连接事件
            RedisHelper.ConnectionFailed += msg => Console.WriteLine($"错误: {msg}");
            RedisHelper.ConnectionRestored += msg => Console.WriteLine($"信息: {msg}");

            // 基本操作示例
            BasicOperationsExample();

            // 发布订阅示例
            PubSubExample();

            //Console.WriteLine("按任意键退出...");
            //Console.ReadKey();

            // 关闭连接
            //RedisHelper.CloseConnection();
        }
        static void BasicOperationsExample()
        {
            try
            {
                // 写入数据（带过期时间）
                bool setResult = RedisHelper.SetString("test_key", "Hello Redis!", TimeSpan.FromMinutes(10));
                Console.WriteLine($"写入结果: {setResult}");

                // 读取数据
                string value = RedisHelper.GetString("test_key");
                Console.WriteLine($"读取结果: {value}");

                // 异步写入
                Task.Run(async () =>
                {
                    bool asyncSet = await RedisHelper.SetStringAsync("async_key", "Async value", TimeSpan.FromMinutes(5));
                    Console.WriteLine($"异步写入结果: {asyncSet}");

                    // 异步读取
                    string asyncValue = await RedisHelper.GetStringAsync("async_key");
                    Console.WriteLine($"异步读取结果: {asyncValue}");
                }).Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"操作错误: {ex.Message}");
            }
        }

        static void PubSubExample()
        {
            const string Channel = "news";

            // 订阅频道
            RedisHelper.Subscribe(Channel, (ch, message) =>
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine($"[{DateTime.Now:T}] 收到消息: {message} (来自频道: {ch})");
                Console.ResetColor();
            });

            Console.WriteLine($"已订阅频道: {Channel}");

            // 发布消息
            for (int i = 1; i <= 5; i++)
            {
                RedisHelper.Publish(Channel, $"新闻更新 #{i}");
                Console.WriteLine($"已发布消息 #{i}");
                Thread.Sleep(1000);
            }

            // 异步发布消息
            Task.Run(async () =>
            {
                for (int i = 6; i <= 10; i++)
                {
                    await RedisHelper.PublishAsync(Channel, $"异步新闻更新 #{i}");
                    Console.WriteLine($"已异步发布消息 #{i}");
                    await Task.Delay(800);
                }
            });
        }

        private void uiButton12_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine($"Task running: {i} - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}");
                    Thread.Sleep(500);
                }
            });
        }

        private void uiButton13_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew((Object state) =>
            {
                string str = state as string;
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine($"Task running: {i} - {str}-{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}");
                    Thread.Sleep(500);
                }
            }, "aaa");
        }

        private void uiButton14_Click(object sender, EventArgs e)
        {
            string Channel = textBox3.Text;
            string prodCode = textBox2.Text;
            RedisHelper.Publish(Channel, $"{prodCode}");
            richTextBox1.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} 已发布消息到频道: {Channel}, 内容: {prodCode}\r\n");
            //Thread.Sleep(1000);
        }

        private void uiButton15_Click(object sender, EventArgs e)
        {
            // 订阅频道
            string Channel = textBox3.Text;
            RedisHelper.Subscribe(Channel, (ch, message) =>
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                //Console.WriteLine($"[{DateTime.Now:T}] 收到消息: {message} (来自频道: {ch})"+"\r\n");
                showInfo($"[{DateTime.Now:T}] 收到消息: {message} (来自频道: {ch})" + "\r\n");
                Console.ResetColor();
            });

            richTextBox1.AppendText($"已订阅频道: {Channel}\r\n");
        }

        private void uiButton16_Click(object sender, EventArgs e)
        {
            // 配置连接字符串（带密码）
            string connectionString = "localhost:6379,password=admin.2025,allowAdmin=true,connectTimeout=5000";

            // 初始化Redis连接
            RedisHelper.Initialize(connectionString);

            // 注册连接事件
            RedisHelper.ConnectionFailed += msg => Console.WriteLine($"错误: {msg}");
            RedisHelper.ConnectionRestored += msg => Console.WriteLine($"信息: {msg}");
        }

        private void ShowInfoStatus(string status)
        {
            if (richTextBox1.InvokeRequired)
            {
                richTextBox1.Invoke(new Action(() => ShowInfoStatus(status)));
            }
            else
            {
                int maxLines = 100;
                string[] lines = richTextBox1.Lines;
                richTextBox1.AppendText(DateTime.Now.ToString("HH:mm:ss.fff") + " " + status + Environment.NewLine);
                if (lines.Length > maxLines)
                {
                    int linesToRemove = 95;
                    string textToKeep = string.Join(Environment.NewLine, lines.Skip(linesToRemove));
                    richTextBox1.Text = textToKeep; // 替换原有内容

                }
                richTextBox1.ScrollToCaret();
            }
        }

        private void uiButton17_Click(object sender, EventArgs e)
        {
            getBarcodePicData();
        }

        private async void getBarcodePicData()
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string url = "https://localhost:44301/api/v1/viewer";
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                {"zplData","^XA^ LH0,0 ^ LL80 ^ PW580 ~DGtemp6,01020,034,iP018iK0C0CiK0E0EI0CFEhY0C0603HF86hY0HC0C06H06L03C0180707FC1F\r\n8I0180601C07807H0E01CI07EH0EH0C0HFI018HFC06186L0670381DC31CH38I018060H70HC0D83B8\r\n36I01B83B81C0HFI018C0C061HCL06303818C30C718I0383E0630CE1DC318H7I019C3181C0C6I01B\r\nC0C0C18CL0C303838C30C618I0380E0E31C618C61863I018C7181C186I0H3C0C0C18CL0CH07838E3\r\n06E18I0780E0E39C618C60C63I018E71C3C186I037HFC0C18CL0CH07838E3H0EK0780E0E38C638E6\r\n0CE38H018E71C3CH0CI07EC0C0D98CL0CH07C38C3H0CK0780E0E3H0638E71CE38H01867183EH0CI0\r\n76CI0F98CL0EH07CH0C318CK0D80EH03H0638E318E38H01860183EH0CJ0HCH01D98CL07H06CH0C31\r\n8CK0D80EH03H0C30E398C38H018601836018J0CHFE1D98CL03C06C01C3F8CJ01980EH0703830E1F0\r\nC38H018603836018I018EF63DBHF86J01E0HC018H38C01HF1980EH0601C30E1F0C39HF186030H601\r\n8I018EF63D80307K0F0HC030318CJ01980EH0CH0630E378C38H0186060H6018I037EF60D80307K03\r\n0FC030318CJ03180EH0CH0630E738C38H01860607E038I07CEF60D80307K038CE060318CJ03180E0\r\n18H0738E61CE38H01860C06703J031EF60D81BM018C60C03H0CJ01FC0E03I0738E61CE38H0186180\r\n6303K01HFE0DIFM018C60C63H0CK0180E0318C738E60CE38H018E18C6303K03EF60D803L0C198618\r\n63H0E18I0180E0619C718C60C63I018E30HC303J01FEF60F80306J0C19861863H0618I0180E0619C\r\n618C61C63I018C30HC303J07B6F60D80307J0E318630C3H063J0180E0C31C61DC318H7I019C618C3\r\n03J0736F60D80307J0F71873FC3H03FJ01C0E0HF0HC0D8H3836I01B87F8C383K036F60C03F07J0DC\r\n3CFBFCF801CJ07E3F8HF0780701E01CI07E07F9E7C3K0H61EI01EhY0H60EJ0EhY0CjT0h0^FO20,15^XGtemp6,1,1^FS ~DGtemp7,00300,010,hJ0EI018R070C03HF8M01801FC0C03018M018H06C7C03018M018H06C6C030\r\n18M03I06C6C03018M03I06C6C03018M03H03HFEC03018M06I06CEC03HF8M06I06C6C03P06I06C6CJ\r\n03M0CI0HC6C3JFM0CI0HC0CH0CO0CI0HC0CH0CI06J018H018C7C01CI07J018H018E1C018I07J018H\r\n0307I01HFC07J03I0607I0181CL03K0718I018L03J0IFCI018L03K07K01806J06K07K01807J06K07\r\nK01807J06K07J0H3807J0CK070EH01FM0CI03FDF8I0FY0CgQ0^FO290,15^XGtemp7,1,1^FS ~DGtemp8,01620,054,kV0CkG0CJ0CEgH018H01CK06J038H038J061CI036hK0EI01CEgH018H01CH0\r\nCH07J038H038J071CI03BJ018J06H0EgP01CI07HCgH018H01E30CH03J038H0380180318I03B8I01C\r\nHFE07HFEgP018183F0CM03C0180707FC1F8038H01HF0C183J038H03BHFC0398I0398J0HC0E0618C0\r\nHFI0F9C0CJ07H0EJ038038H01HFC031C3L0670381DC31CH38030181E36C1IFEH038H03818H03BJ03\r\n98J0DC0C079BC0FEI071C0CJ0D81BJ06C0ECH03838031HFL06303818C30C719JF83636C18H0C0C3I\r\n03E18I03H018186J03B6H06DBC0CJ03187CI01DC3B8I0HE0HCH0303H031838K0C303838C30C61803\r\nI036F6C38H0C0IFE03F18H0C6701IFEJ0I3H06DEC0CJ03181CI018C318I0C618CH0607H03D87L0CH\r\n07838E306E1803I036F6C380380C30E0FE18H0IF01818K0H61C06DHE0CJ03181CI018C318I0C618I\r\n078601HF36L0CH07838E3H0EI06I07EF6C0IF80C30E0FC18H0C0601818J0I60C06DCE0CJ03181CI0\r\n38E71CH01C738I0DCEH0H73M0CH07C38C3H0CI06I076F6CH0EI0C30E0F818H0C0601818J036IC061\r\nCE0CJ03181CI038E71CH01C738H018DCH0763M0EH07CH0C318CI06I076F6CH0CI0C30E0F818H0C06\r\n01818CI03F8HC07HFE0CJ03B01CI038E71CH01C738H018D8H0763M07H06CH0C318CI0EI0F6F6C018\r\n6H0C30E1F818H0C0601819CI03C0CH0618C0FCI03B01CI030E61CH0187378I038H079BM03C06C01C\r\n3F8CI0C060F6F6C0303H0C38E1B018H0C0601FD9CJ0C0C6H018H0CEI01B01CI030E61CH01873HCI0\r\n7I0FDFH06J01E0HC018H38CI0IF036F6C060380C6CE03018H0C06018D983FE0DHFEH018C0C6I01B0\r\n1CI030E61CH018738CI0EI0FDBC07K0F0HC030318CH01E06036F6C0IF80CH6E03018H0HFE018HD8J\r\n0D9EH0IFCH07I01B01CI030E61CH018738EH01C0C0FDB607K030FC030318CH01E06036F6C076180H\r\nC7E03018H0D86018CF8J0C3EH0C18I07I01B01CI030E61CH0187306H03HFC1B1B607K038CE060318\r\nCH03606036F6CH07180HC3E030180H0CH018CFJ0183FI018I07I01E01CI038E71CH01C7306H0780C\r\n1BH37M018C60C03H0CH03606037B6CH07I0D83E03818H06EH018CFJ0183FI0187H07I01E01CI038E\r\n71CH01C7306H0D80C1BI3M018C60C63H0CH0H60603786CH07I0F03E03C1803763018CFJ0786F83JF\r\n1C7J0E01CI038E71CH01C738603980CK3L0C19861863H0E18C60603180C0IF80EH0E03E1803H6181\r\n8C63I0386D8K01C7J0E01CI018C318I0C638606180C036H386J0C19861863H0618C606031E0CH07I\r\n0CH0E0H61803H6DC18CF3I018CDC06I01C6J0C01C0C018C3186H0C618EH0180C036H307J0E318630\r\nC3H06318606031B0CH07I0CH0E0H6180760HCH3CF3I0198CE06IC0C6J0C01C1E01DC3B8FH0HE18CH\r\n0180C03C3H07J0F71873FC3H03FH06060I30CH07I0CH0E060180H60HC319HBI0198CF06CE60HCJ0C\r\n01C1EH0D81B0FH06C0DCH01HFC0303H07J0DC3CFBFCF801CH07FE0I38CH07060CH0E0C0180E60E03\r\n031FI03B0CH0EH67078J0C07F0CH07H0E06H03807I0180C030FgH06060361FCH070E0C03C0C0F8H0\r\n7FE03060FI0380CH0CH67gP018I0307gH0E0603C03C3FDF80C01C18078H03FC060C07I0180C01CH6\r\nL0gR06gL03H018L0CL03nH0^FO20,45^XGtemp8,1,1^FS ~DGtemp9,00360,012,hP03J01CW03H0181CV03B060C18U03E3HF0E18N0CJ0FH0CH3H0618M01CI01\r\n980CH3H07B83L01CI019C0CH3H07BHFL01CI038C0CH3H01B07L03CI038C0CH3H01B06L03CI018C0H\r\nF3H03I6L03EK0C0HF3H036ECL03EK0C3DF3603CEM036J0180CHFE06CEM036J07H0DF3H078FH06J0H\r\n61HF0380DB3H060FH07J0H6K0C0CH3H060FH07J07EK0C0CH303C0FH07J067K0E0DE3H0C0FM063K0E\r\n0F63H0C198L063I018E0E63H0C198L0C3I038E3863H0C19806J0C3I038C70C3H0C30C07J0C3I038C\r\n61C360C30E07J0C38H0198019HF0C60607I01E7CI0FH03J0HC078T06J01803U0CJ03hG0^FO360,15^XGtemp9,1,1^FS ^FO20,95^BY2,3.0:1,50^BAN,50,Y,N,N^FD030F1148FRANNNN002^FS ~DGtemp10,00900,030,lI078060ChR0C06C0606W06U018W0C06E0607W06U018W0C0H60603H07803\r\n01E1F7HFI061EH0C0787DF7F8018780301E1F7DHFJ0C0H6060H30CE070H30E38DCH0CH381C0HC38E\r\n31C030CE070H30E38C7J0CIF07BHF8C6070H38E38CEH0C3181C0CE38E30C030C6070H38E38C3J0D8\r\n603FE03186070718E38C6H0C6181C1C638E30C03186070718E38C3J0F06H0H60618H0F0718E38C70\r\n186H03C1C638E3I0618H0F0718E38C18H07F86H060C618H0F0318E38C70186H03C0C638E3I0618H0\r\nF0318E38CK0CFEC061DC18H0F8018E38C30186H03EH0638E3I0618H0F8018E38CK0CDHE0618E1CH0\r\nF8018E38C30307H03EH0638EH3H0C1CH0F8018E38C6J0CDEC06F070EH0D8030E38C303038036H0C3\r\n8EH3H0C0EH0D8030E38C6J0CDEC07E070780D80E0HF8C30301E0360383FE3FH0C0780D80E0HF8FEJ\r\n0CDFC0H60303C198070E38C306H0F0H601C38EH301803C198070E38CEJ0CDF81ECI01E198018E38C\r\n306H078H6H0638EH301801E198018E38C6J0CHF83E7FEH061F8018E38C306H0187EH0638E3H018H0\r\n61F8018E38C6J0CDF83606I0719C01CE38C30CH01C67H0738E3H03I0719C01CE38C6J0F0380606I0\r\n318C01CE38C30CI0C63H0738E3H03I0318C01CE38CK0E03H0606I0318C31CE38C70CI0C630C738E3\r\nH03I0318C31CE38CJ0781F30606018H30C71CE38C70C060HC31C738E3H03018H30C71CE38CJ070F7\r\nB0606018H30C718E38C618060HC31C638E30C6018H30C718E38CK03CFB060601C630C718E38CE180\r\n718C31C638E30C601C630C718E38CK030DF060631HE30EH30E38DC1807B8C38HC38E31C601HE30EH\r\n30E38CL018F060631B879F1E1F7HF03H06E1E7C787DF7FHC01B879F1E1F7FEL030F3EHFET03V0Cg0\r\n6070EhU0CkW0^FO500,30^XGtemp10,1,1^FS ~DGtemp11,00960,032,pM018U06U018gO018U06U018T01EH0C0787DF0EH0187803H0E0HF9EI061E\r\nH0C0387DF0EH0187803H0E1F7FEF0H381C0HC38E1B8030CE0703B8638CI0CH381C0HE38E1B8030CE\r\n0703B8E38C603181C0CE38E318030C6070318618CI0C3181C0C638E318030C6070318E38C606181C\r\n1C638E31803186070718618CI0C6181C1C638E31803186070718E38HC06H03C1C638E7180618H0F0\r\n71C60HCH0186H03C1C738E7180618H0F071CE38HC06H03C0C638E6I0618H0F071C6H0CH0186H03C1\r\nC738E6I0618H0F071CE38D806H03EH0638E6I0618H0F87186H0CH0186H03E1C638E6I0618H0F8718\r\nE38D807H03EH0638E6I0C1CH0F8018630CH0307H03EH0638E6I0C1CH0F8018E38FH038036H0C38E6\r\nI0C0EH0D8018630CH03038036H0638E6I0C0EH0D8018E38FH01E0360383FE6I0C0780D80387F0CH0\r\n301E036H0E3FE6I0C0780D8038HF8FI0F0H601C38E6H01803C198030670CH06H0F0H6H0C38E6H018\r\n03C198030E38F8H078H6H0638E6H01801E198060630CH06H078H601838E6H01801E198060E38D8H0\r\n187EH0638E61C18H061F8060630CH06H0187E01838E61C18H061F8060E38D8H01C67H0738E6183I0\r\n719C0C0630CH0CH01C6703038E6183I0719C0C0E38DCI0C63H0738E6183I0318C1806H0CH0CI0C63\r\n06038E6183I0318C180E38HCI0C630C738E6183I0318C18C6H0CH0CI0C6306H38E6183I0318C18CE\r\n38HC060HC31C738E7183018H30C30C6H0CH0C060HC30CH38E7183018H30C30CE38CE060HC31C638E\r\n3186018H30C30C6H0C318060HC30CH38E3186018H30C30CE38C60718C31C638E318601C630C6186H\r\n0C3180718C318638E318601C630C618E38C607B8C38HC38E1B0601HE30E7F86H0C71807B8C39FE38\r\nE1B0601HE30E7F8E38C706E1E7C787DF0E0C01B879F7F9F01HF3H06E1E7DFE7DF0E0C01B879F7F9F\r\n7FEF8T0CU03V0CpN0^FO500,60^XGtemp11,1,1^FS ^FO500,90^BY2,3.0:1,50^BAN,50,Y,N,N^FD030F1148FRANNNN002^FS^FO30,0^XGR:11.GRF,1,1^FS^XZ" },
                {"printDensityDpmm",8 },
                {"labelWidth","102" },
                {"labelHeight","152"}
            };
            HttpResponseResult result = await HttpClientHelper.GetPostJsonResult(url, parameters);
            Console.WriteLine($"请求结果: {result.IsSuccess}, 状态码: {result.StatusCode}, 内容: {result.Content}");

            Dictionary<string, object> responseData = jss.Deserialize<Dictionary<string, object>>(result.Content);
            var labelList = (ArrayList)responseData["labels"];

            string aaa = labelList.GetType().ToString();
            if (labelList.Count == 0)
            {
                Console.WriteLine("没有找到标签数据");
                return;
            }

            Dictionary<string, object> labelData = (Dictionary<string, object>)labelList[0];
            string base64Image = labelData["imageBase64"].ToString();

            pictureBox1.Image = null; // 清空之前的图片
            byte[] imgBytes = Convert.FromBase64String(base64Image);
            pictureBox1.Image = System.Drawing.Image.FromStream(new System.IO.MemoryStream(imgBytes));
        }

        private void uiButton18_Click(object sender, EventArgs e)
        {

            CallMain();
        }

        private async void CallMain()
        {
            Task<string> resultA = A();
            uiRichTextBox1.AppendText("开始执行任务A" + await resultA + Environment.NewLine);
            Task<string> resultB = B();
            uiRichTextBox1.AppendText("开始执行任务B" + await resultB + Environment.NewLine);
            Task<string> resultC = C();
            uiRichTextBox1.AppendText("开始执行任务C" + await resultC + Environment.NewLine);
        }

        private async Task<string> A()
        {
            string result = await Task.Run(() =>
            {
                Thread.Sleep(2000); // 模拟耗时操作
                return "A方法执行完成";
            });
            return result;
        }
        private async Task<string> B()
        {
            string result = await Task.Run(() =>
            {
                Thread.Sleep(2000); // 模拟耗时操作
                return "B方法执行完成";
            });
            return result;
        }
        private async Task<string> C()
        {
            string result = await Task.Run(() =>
            {
                Thread.Sleep(2000); // 模拟耗时操作
                return "C方法执行完成";
            });
            return result;
        }

        private void uiButton19_Click(object sender, EventArgs e)
        {
            string prodCode = uiTextBox3.Text;
            GetCheckResult(prodCode);
        }
        private async Task<string> GetCheckResult(string prodCode)
        {
            
            JavaScriptSerializer jss = new JavaScriptSerializer();
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
            {
                {"prodCode" ,prodCode},{"checkMesResult","OK"}
            };
            string jsonData = jss.Serialize(keyValuePairs);


            string result = await tcpClientDevice.SendRcvAsync(prodCode);
            ThreeDCheckParams dicResult= null;
            if (!result.Equals(""))
            {
                dicResult = jss.Deserialize<ThreeDCheckParams>(result);
                List<string> picPath = dicResult.picPath;
                string path1 = picPath[0];
                string path2 = picPath[1];
                initPicBox(path1, pic1);
                initPicBox(path2, pic2);
                uiRichTextBox1.AppendText(DateTime.Now.ToString("yyyyMMddHHmmss.fff") + " 图片1：" + path1 + Environment.NewLine);
                uiRichTextBox1.AppendText(DateTime.Now.ToString("yyyyMMddHHmmss.fff") + " 图片2：" + path2 + Environment.NewLine);
            }
            

            uiRichTextBox1.AppendText(DateTime.Now.ToString("yyyyMMddHHmmss.fff")+" 检测结果：" + result + Environment.NewLine);
            return result;
        }

        private void initPicBox(string filePath,PictureBox picBox)
        {
            if (filePath.Equals(""))
            {
                filePath = "D:\\imageLog\\20250327\\p1234_01.png";
            } 
            Bitmap originalImage = new Bitmap(filePath);
            //pictureBox.Size= originalImage.Size; // 设置PictureBox大小与图片一致
            picBox.Image = originalImage;
            picBox.Invalidate(); // 重绘标记
        }

        private void uiButton20_Click(object sender, EventArgs e)
        {
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TcpClientDevice.ShowData += ShowInfoStatus;
            tcpClientDevice.Connect();
            tcpClientDevice.ReConnect();
            tcpClientDevice.DataCollection();
            //InitializeAsync();
        }

        
        private void uiButton21_Click(object sender, EventArgs e)
        {
            
        }

        private async void Waitesult()
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void uiButton22_Click(object sender, EventArgs e)
        {
            alg.SendHexCmd("aaa");
            byte[] result = alg.ReceiveHexData();
            var infoStuct=alg.ParseSystemInfo(result );
            string[] hexArray = result.Select(b => b.ToString("X2")).ToArray();

            string strResult = string.Concat(hexArray);//String.Join(",", result);//Encoding.UTF8.GetString(result);
            ShowInfoStatus(strResult);
        }

        private void uiButton23_Click(object sender, EventArgs e)
        {
            using (var httpClient = new HttpClientSyncHelper())
            {
                // 添加自定义请求头
                httpClient.AddHeader("appId", "Bearer token123");
                httpClient.AddHeader("appKey", "12312312");
                Dictionary<string, Object> parameters = new Dictionary<string, Object>()
             {
                {"serviceId","AAA"},
                {"interfaceCode","BBB"},
                {"factoryCode","CC"},
                {"mesVersion","CD"  },
                {"url","DD" },
                {"body","DD" }

             };


                // POST请求示例（JSON）
                ShowInfoStatus("\n===== POST(JSON)请求 =====");
                
                var postResult = httpClient.Post("http://localhost:9090/api/v1/dms/redirect", parameters);
                string result=Newtonsoft.Json.JsonConvert.SerializeObject(postResult);
                ShowInfoStatus(result);

                
            }

            
        }

        private void uiButton24_Click(object sender, EventArgs e)
        {
            ProductiveParam productiveParam = new ProductiveParam()
            {
                para_name = "测试参数",
                value = "123",
                up_limit = "200",
                down_limit = "50",
                tag = "测试标签"
            };
            CheckDataItemResult(ref productiveParam);
            ProductiveParam test;
            CheckDataItemResultOut(out test);
           

            ProductiveParam productiveParam1 = new ProductiveParam()
            {
                para_name = "test1",
                value = "123",
                up_limit = "200",
                down_limit = "50",
                tag = "测试标签"
            };
            List<ProductiveParam> paramList= new List<ProductiveParam>();
            paramList.Add(productiveParam);
            paramList.Add(productiveParam1);

            ProductiveParam productive =paramList.Find(ele => ele.para_name.Equals("aaa"));


            string dtStr = DateTime.Now.ToString();
        }
        public string CheckDataItemResult(ref ProductiveParam testItem)
        {
            string result = "NG";

            if (testItem != null )
            {
                float realVal = testItem.value.ToFloat();
                if (realVal > 12f && realVal < 133f)
                {
                    testItem.tag = "OK";
                    return "OK";
                }
            }

            return result;
        }
        public string CheckDataItemResultOut(out ProductiveParam testItem)
        {
            string result = "NG";
            testItem = new ProductiveParam() { value="15"};
            if (testItem != null)
            {
                float realVal = testItem.value.ToFloat();
                if (realVal > 12f && realVal < 133f)
                {
                    testItem.tag = "OK";
                    return "OK";
                }
            }

            return result;
        }

        private async void uiButton25_Click(object sender, EventArgs e)
        {
            dataCount++;
            double value = Math.Round(random.NextDouble() * 100, 2);

            try
            {
                // 调用HTML中定义的JavaScript函数
                await webView.CoreWebView2.ExecuteScriptAsync(
                    $"addDataPoint('点{dataCount}', {value})");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"错误: {ex.Message}");
            }
        }
        private async void InitializeAsync()
        {
            // 初始化WebView2环境
            //await webView.EnsureCoreWebView2Async(null);

            // 获取HTML文件路径
            string htmlPath = Path.Combine(Directory.GetCurrentDirectory(), "webEmbed\\chart.html");

            // 加载本地HTML文件
            //webView.CoreWebView2.Navigate(htmlPath);
            webView.Source = new Uri(htmlPath);
        }

        private void uiButton5_Click_1(object sender, EventArgs e)
        {

        }

        private void uiButton26_Click(object sender, EventArgs e)
        {
            string targetStr = @"{""code"":""000000"",""count"":1,""data"":{""flag"":false,""code"":""GB000074"",""map"":{""factoryCode"":""ZZJ0"",""stationCode"":""HHGW1"",""orderType"":""QC02"",""orderNumber"":""PO20250625022"",""orderId"":""1937694755381579777"",""operationCode"":""HHGX1"",""showNumFlag"":""N"",""materialVersion"":""A"",""ispass"":""1764493262650494977,comein"",""lineCode"":""HHCX"",""scheduleNum"":20.0000,""inputNum"":9.000000,""routeId"":""HHGYLX:3:1937421138596990977"",""operationId"":""1764493262650494977"",""operationParamPoList"":[{""paramCode"":""operation_type"",""operationCode"":""HHGX1"",""operationId"":""1764493262650494977"",""id"":""1906535091774382085"",""paramId"":""1749385579184431105"",""paramValue"":""ZP""},{""paramCode"":""auto_coefficient"",""operationCode"":""HHGX1"",""operationId"":""1764493262650494977"",""id"":""1906535091774382084"",""paramId"":""174938552024020402"",""paramValue"":""0""},{""paramCode"":""plan_auto_flag"",""operationCode"":""HHGX1"",""operationId"":""1764493262650494977"",""id"":""1906535091774382083"",""paramId"":""174938552024020401"",""paramValue"":""1""},{""paramCode"":""ISOP"",""operationCode"":""HHGX1"",""operationId"":""1764493262650494977"",""id"":""1906535091774382082"",""paramId"":""1703651715748532225"",""paramValue"":""Y""}],""sn"":""0G0F1250625005"",""scheduleId"":""1937694797449277441"",""shopOrderBomId"":""1937694769220370434"",""stationId"":""1764492650384986114"",""nonTraceabilityBatch"":2,""snContinues"":-1,""processTemplateCode"":""UI_TR_ZP"",""operationConfigData"":{""outgoingBarcodeBindingType"":""0"",""needAssembler"":""0"",""editUserId"":""1727499677749485569"",""addTime"":""1709522951175"",""addUserId"":""1727499677749485569"",""outgoingBarcodeBinding"":""0"",""dataStatus"":""0"",""editTime"":""1743388362225"",""lineClearanceConfirmation"":""0"",""multiScheduleBinding"":""0"",""assembleOrder"":""0"",""productionChangeType"":""0"",""foolProofingInterception"":""0"",""feedType"":""0"",""materialStopType"":""0"",""operationId"":""1764493262650494977"",""productProcessTemplateId"":""1506803728081858562"",""id"":""1764493262658883586"",""productNumberBinding"":""0"",""consumeType"":""0""},""lineId"":""1764492577622200322"",""operationName"":""HH工序1"",""materialCode"":""14835391-00"",""materialId"":""1770402539172921346"",""processTemplateId"":""1506803728081858562"",""materialName"":""汽车PCBA_SFH-4123816/80_右侧室内灯阅读灯_贴片"",""nextSN"":0,""routeUrl"":""A"",""containerCode"":""TR"",""scheduleNumber"":""MO202506251964""},""mesg"":""当前SN已被使用，SN号0G0F1250625005 不在当前工序生产，请前往工序：HH工序3 生产！ [GB000074]""},""fail"":false,""mesg"":""处理成功"",""success"":true,""time"":""1752646375680""}";
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ResponseResult result = jss.Deserialize<ResponseResult>(targetStr);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            string keyCode=textBox4.Text;
            textBox5.Text= GenerateProdCode.Generate(keyCode);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var collection = new UserCollection();
            collection.Users.Add(new User { Name = "张三", Age = 25, Email = "zhangsan@example.com" });
            collection.Users.Add(new User { Name = "李四", Age = 30, Email = "lisi@example.com" });

            propertyGrid1.SelectedObject = collection;
        }
    }
    public class  ThreeDCheckParams
    {
        public string prod_code { get; set; }
        public List<string> picPath { get; set; }
        public List<ProductiveParam> productive_param { get; set; }
        
        public string check_result { get; set; }
        //public string check_start_time { get; set; }
        //public string check_end_time { get; set; }
        //public string user_id { get; set; }
    }
    //产品结果
    public class ProductiveParam
    {
        public string para_name { get; set; }
        public string value { get; set; }
        public string up_limit { get; set; }
        public string down_limit { get; set; }
        public string tag { get; set; }
    }
}
